#include "FileTransferFifo.h"

FileTransferFifo::FileTransferFifo(string fileName) {
	this->name = fileName;
    this->isDestroyed = false;

	// Se crea el fifo.
	mkfifo(this->name.c_str(), S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);

	// Se inicializa el file descriptor en -1.
	this->fd = -1;
}

int FileTransferFifo::writeData(char* data, int dataSize) {
	// Se abre el file descriptor para escritura.
	if (this->fd == -1) {
		this->fd = open(this->name.c_str(), O_WRONLY);
	}

	// Se escriben los datos en el fifo.
	int result = write(this->fd, (const void *)data, dataSize);

	return result;
}

int FileTransferFifo::readData(char* buffer, int buffSize) {
	// Se abre el file descriptor para lectura.
	if (this->fd == -1) {
		this->fd = open(this->name.c_str(), O_RDONLY);
	}

	// Se leen los datos del fifo.
	int result = read(this->fd, (void *)buffer, buffSize);

	return result;
}

void FileTransferFifo::destroy() {
	if (!this->isDestroyed) {
		if (this->fd != -1) {
			close(this->fd);
		}

		unlink(this->name.c_str());
		this->isDestroyed = true;
	}
}

FileTransferFifo::~FileTransferFifo() {
	if (!this->isDestroyed) {
		if (this->fd != -1) {
			close(this->fd);
		}
	}
}

